package com.upc.tp.timeplanning.controller;

import com.upc.tp.timeplanning.entity.*;
import com.upc.tp.timeplanning.mapper.RuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/rule", method = {RequestMethod.POST, RequestMethod.GET})
public class RuleController {

    @Autowired
    RuleMapper ruleMapper;

    @RequestMapping("/getAll")
    public List<Rule> getAll(){
        List<Rule> list = ruleMapper.getAll();
        return list;
    }


    @RequestMapping("/getByStuUsername")
    public ResBody getByStuUsername(@RequestBody Student student){

        ResBody resBody;
        try{
            List<Rule> list = ruleMapper.getByStuUsername(student.getUsername());
            resBody = new ResBody(100,"success",list);
        }catch (Exception e ){
            return new ResBody(0,"fail",null);
        }

        return resBody;
    }

    @RequestMapping("/getByParUsername")
    public ResBody getByParUsername(@RequestBody Parent parent){

        ResBody resBody;
        try{
            List<Rule> list = ruleMapper.getByParUsername(parent.getUsername());
            resBody = new ResBody(100,"success",list);
        }catch (Exception e ){
            return new ResBody(0,"fail",null);
        }

        return resBody;
    }

    @RequestMapping("/getById")
    public ResBody getById(@RequestBody Task task){

        ResBody resBody;
        try{
            List<Rule> list = ruleMapper.getById(task.getRule_id());
            resBody = new ResBody(100,"success",list);
        }catch (Exception e ){
            return new ResBody(0,"fail",null);
        }

        return resBody;
    }

    @RequestMapping("/makeRule")   //制定规则
    public ResBody makeRule(@RequestBody Rule rule){

        ResBody res;
        try{
            ruleMapper.makeRule(rule.getStu_username(),rule.getPar_username(),rule.getRule_name(),rule.getCycle());
            res = new ResBody(100,"success",null);
        }catch (Exception e){
            return new ResBody(0,"fail",null);
        }
        return res;
    }

    @RequestMapping("/delete")
    public ResBody delete(@RequestBody Rule rule){

        ResBody resBody;
        try{
            if(rule.getRule_id()==1||rule.getRule_id()==2||rule.getRule_id()==3||rule.getRule_id()==4){
                return new ResBody(-1,"can't delete",null);
            }
            else{
                ruleMapper.delete(rule.getRule_id());
                resBody = new ResBody(100,"success",null);
            }
        }catch (Exception e ){
            return new ResBody(0,"fail",null);
        }

        return resBody;
    }
}
